""" 分时段计算每个时段最大并发任务数 """
import pandas as pd 
import numpy as np
import json 

# 设置日期时间列表
date = ["2019-"+"01-"+str(14+i) for i in range(7)]
time = ["2:30", "05:30", "7:00", "14:30", "19:00"]

# 组装生成日期时间series
date_time_stamp = [d + ' ' + t for d in date for t in time]
date_time_stamp = [pd.Timestamp(i) for i in date_time_stamp]
# 获取间隔之间的任务数据
# sub_task_data = task_data[(task_data["start_time"] >= pd.Timestamp(date_time_stamp[0])) & 
#                             (task_data["end_time"] <= pd.Timestamp(date_time_stamp[1]))]
max_parallel_task = {}

def compute_max_multi_task(task_data):
    for i in range(0,len(date_time_stamp)-1):
        time_interval = [date_time_stamp[i], date_time_stamp[i+1]]
        # 提取时间间隔内的任务信息
        sub_task_data = task_data[(task_data["ready_time"] >= time_interval[0]) & 
                                    (task_data["ready_time"] <= time_interval[1])]
        
        #获取任务持续时间
        sub_task_data_duration = sub_task_data["end_time"] - sub_task_data["ready_time"]
        #取得最小时间窗口
        min_time_delta = sub_task_data_duration.min()
        
        multi_task_dict = {} 

        # 初始化检查点
        check_point = time_interval[0]

        # 对每个时间节点判断：
        for k in range(30):
            # 初始化task_number
            multi_task_number = 0 
            
            check_point += min_time_delta

            # 检查点超出区间，终止
            if check_point > time_interval[1]:
                break
            else: 
            # 分别对每个任务进行判断是否并行
                for j in range(sub_task_data.shape[0]):
                    ready_time, end_time = sub_task_data.iloc[j]["ready_time"], sub_task_data.iloc[j]["end_time"]
                    if (ready_time <= check_point) & (end_time >= check_point):
                        multi_task_number += 1
                    elif ready_time >= check_point:
                        break
                    else:
                        continue
                # 将每个检查点的任务数目存入multi_task_dic
                multi_task_dict[str(check_point)] = multi_task_number
        
        MAX_MULTI_TASKS = max(multi_task_dict.values())
        print(multi_task_dict.values())
        max_parallel_task[str(date_time_stamp[i])+"-"+ str(date_time_stamp[i+1])] = MAX_MULTI_TASKS

    print(max_parallel_task)
    with open(r"data\max_multi_task.json","w+") as f:
        _json = json.dumps(max_parallel_task)
        f.write(_json)

if __name__ == "__main__":
    task_data = pd.read_csv(r"data\total_tasks.csv", converters={"ready_time":pd.to_datetime,"start_time":pd.to_datetime,"end_time":pd.to_datetime})
    print("="*20+"导入数据成功"+"="*20)
    compute_max_multi_task(task_data)